package com.ebupt.migu.music.userlist.controller;

import com.ebupt.migu.music.common.auth.AuthBaseUtils;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.entity.StaticUser;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.DateUtil;
import com.ebupt.migu.music.common.util.ReqestParamUtil;
import com.ebupt.migu.music.common.util.RestClientUtils;
import com.ebupt.migu.music.system.entity.SysUser;
import com.ebupt.migu.music.userlist.entity.UserWhiteList;
import com.ebupt.migu.music.userlist.service.WhiteListService;
import com.mysql.cj.util.StringUtils;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizm
 */
@RestController
@RequestMapping("/whitelist")
public class WhiteListController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private WhiteListService wlService;
    @Autowired
    private RestClient restClient;
    // 文件默认保存路径
    @Value("${path.user_list_path}")
    private String FILE_UPLOAD_PATH;
    @Value("${spring.elasticsearch.alias}")
    private String esIndex;
    @Value("${spring.elasticsearch.esType}")
    private String esType;


    @RequestMapping("/checkWhiteList")
    public ResultObject<Object> check() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        List<UserWhiteList> list= wlService.checkWhiteList(paramMap);
        if(null!=list&&list.size()>0){
            retObj.setCode("0000");
            retObj.setMsg("白名单中已存在该号码");
        }else{
            retObj.setCode("0001");
            retObj.setMsg("白名单中不存在该号码");
        }
        return retObj;
    }

    @RequestMapping("/addWhiteList")
    public ResultObject<Object> add() {
        // 获取用户登录信息
        SysUser user = AuthBaseUtils.getSessionUser(request);
        int insertNo=0;
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        paramMap.put("creatorId",null!=user?user.getLoginName():"");
        List<UserWhiteList> list= wlService.checkWhiteList(paramMap);
        if(null!=list&&list.size()>0){
            retObj.setCode(StatusEnum.ADD_WHITELIST_ERROR.getCode());
            retObj.setMsg("手动添加白名单失败：白名单中已存在该号码");
        }else {
            String msisdn= (String) paramMap.get("mobile");
            //es反查
            List<StaticUser> userList=RestClientUtils.getUser(restClient,msisdn,esIndex,esType);
            if(null!=userList&&userList.size()>0){
                for (int i = 0; i <userList.size() ; i++) {
                    StaticUser esUser=userList.get(i);
                    paramMap.put("uid",esUser.getUid());
                    paramMap.put("imei",esUser.getImei());
                    paramMap.put("idfa",esUser.getIdfa());
                    paramMap.put("whiteId",System.currentTimeMillis());//时间戳，做排序用
                    paramMap.put("createTime",new Date());
                    Integer id = wlService.addWhiteList(paramMap);
                    if(null!=id){
                        insertNo++;
                    }else{
                        throw new MyException(StatusEnum.ADD_WHITELIST_ERROR,StatusEnum.ADD_WHITELIST_ERROR.getMsg());
                    }
                }
            }
            retObj.setData(null);
            retObj.setMsg("手动添加白名单成功,条数："+insertNo);
        }
        return retObj;
    }

    @RequestMapping("/delWhiteList")
    public ResultObject<Object> delete() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        Integer total =wlService.delWhiteList(paramMap);
        if(total>0){
            retObj.setData(total);
            retObj.setMsg("删除白名单成功");
        }else{
            throw new MyException(StatusEnum.DEL_WHITELIST_ERROR,StatusEnum.DEL_WHITELIST_ERROR.getMsg());
        }
        return retObj;
    }

    @RequestMapping("/delWhiteListBatch")
    public ResultObject<Object> deleteBatch() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        Integer total =wlService.delWhiteListBatch(paramMap);
        if(total>0){
            retObj.setData(total);
            retObj.setMsg("批量删除白名单成功,个数："+total);
        }else{
            throw new MyException(StatusEnum.DEL_WHITELIST_ERROR,StatusEnum.DEL_WHITELIST_ERROR.getMsg());
        }
        return retObj;
    }

    @RequestMapping("/list")
    public ResultObject<Object> list() {
        ResultObject<Object> retObj = new ResultObject<Object>();
        Map<String,Object> paramMap = ReqestParamUtil.getParams(request);
        retObj.setMsg("查询白名单列表成功");
        retObj.setData(wlService.queryByPage(paramMap));
        return retObj;
    }
    /**
     * 导入模板下载
     * @return
     * @author lizm
     */

    @RequestMapping("/exportTemplate")
    public HttpServletResponse downloadDataTemplate() {
        String fileName="whiteListTemplate.csv";
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        String realpath=classpath+"file/"+fileName;
        try {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=\""+ fileName+ "\"");
            request.setCharacterEncoding("UTF-8");
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(realpath);
            byte[] b = new byte[2048];
            int i = 0;

            while ((i = fis.read(b)) > 0) {
                os.write(b, 0, i);
            }

            fis.close();
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 读取CSV文件
     * @return
     */
//    @RequestMapping("/csvRead")
//    @ResponseBody
//    public ResultObject csvRead(){
//        Map<String, Object> paramMap = ReqestParamUtil.getParams(request);
//        String path = paramMap.get("path").toString();
//        ResultObject res = new ResultObject();
//        List<String[]> data = CSVUtils.csvRead(path);
//        res.setData(data);
//        CSVUtils.csvWrite("D:\\csv","\\redBag", data);
//        return res;
//    }
    /**
     * 白名单导入
     * @return
     */
    @PostMapping(value = "/csvImport")
    @ResponseBody
    public ResultObject csvImport(@RequestParam("file") MultipartFile file){
         // 获取用户登录信息
         SysUser user = AuthBaseUtils.getSessionUser(request);
    	 ResultObject res = new ResultObject();
    	 // 校验文件是否为空，格式是否正常
         boolean isExcelFile = CSVUtils.validateUploadFile(file, "csv");
         if (!isExcelFile) {
             throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
         }
         Date date = new Date();
         String timeStr = DateUtil.parseDateToStr(date, DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
         String newPath=FILE_UPLOAD_PATH+timeStr+"_"+file.getOriginalFilename();
         //上传附件到指定目录
         //导入不需要保存附件，如果保存附件，因为流只能读取一次，那么csvRead要改用传上传文件path的方法
         CSVUtils.upload(file,newPath);
         //数据入库
         //List<String[]> data = CSVUtils.csvRead(file);
         List<String[]> data = CSVUtils.csvRead(newPath,',');
         int insertNumber=0;
         int skipNumber=0;
         if(null!=data&&data.size()>0) {
             for (int i = 1; i < data.size(); i++) {//跳过首行
                 Map<String, Object> checkMap = new HashMap<String, Object>();
                 checkMap.put("mobile", data.get(i)[1]);
                 List<UserWhiteList> list = wlService.checkWhiteList(checkMap);
                 if (null != list && list.size() > 0) {//跳过白名单已存在行
                     skipNumber++;
                     continue;
                 } else {
                     String mobile = data.get(i)[1];
                     if (StringUtils.isNullOrEmpty(mobile)) {//跳过手机号码为空行
                         skipNumber++;
                         continue;
                     } else {
                         Map<String, Object> map = new HashMap<String, Object>();
                         map.put("userName", data.get(i)[0]);
                         map.put("mobile", data.get(i)[1]);
                         map.put("remark", data.get(i)[2]);
                         map.put("creatorId",null!=user?user.getLoginName():"");
                         //es反查
                         List<StaticUser> userList = RestClientUtils.getUser(restClient, data.get(i)[1], esIndex, esType);
                         if (null != userList && userList.size() > 0) {
                             for (int j = 0; j < userList.size(); j++) {
                                 StaticUser esUser = userList.get(j);
                                 map.put("uid", esUser.getUid());
                                 map.put("imei", esUser.getImei());
                                 map.put("idfa", esUser.getIdfa());
                                 map.put("whiteId", System.currentTimeMillis());//时间戳，做排序用
                                 map.put("createTime", new Date());
                                 Integer id = wlService.addWhiteList(map);
                                 if (null != id) {
                                     insertNumber++;
                                 } else {
                                     throw new MyException(StatusEnum.ADD_WHITELIST_ERROR, StatusEnum.ADD_WHITELIST_ERROR.getMsg());
                                 }
                             }
                         }
                     }
                 }
             }
         }
         res.setMsg("导入成功条数："+insertNumber+",跳过条数："+skipNumber);
    	 return res;
    }
    }

